﻿using BasicInformation.Domain;
using BasicInformation.Infrastructure.Iml;
using BasicInformation.Infrastructure.Interface;
using BasicInformation.ReadAPI.Application.Command.FuelCostsCommand;
using MediatR;
using Microsoft.AspNetCore.Mvc.RazorPages;
using PublicCommon;

namespace BasicInformation.ReadAPI.Application.CommandHandler.FuelCostsCommandHandler
{
    public class FuelCostsListCommandHandler : IRequestHandler<FuelCostsListCommand, PageResult<FuelCosts>>
    {
        private readonly IFuelCostsRepository fuelCostsRepository;

        public FuelCostsListCommandHandler(IFuelCostsRepository fuelCostsRepository)
        {
            this.fuelCostsRepository = fuelCostsRepository;
        }

        public async  Task<PageResult<FuelCosts>> Handle(FuelCostsListCommand request, CancellationToken cancellationToken)
        {
            var list = fuelCostsRepository.GetList().Result.Where(x => !x.IsDel).AsQueryable();
            if (!string.IsNullOrEmpty(request.FuelNumber))
            {
                list = list.Where(x => x.FuelNumber.Contains(request.FuelNumber));
            }
            if (!string.IsNullOrEmpty(request.ResPerson))
            {
                list = list.Where(x => x.ResPerson.Contains(request.ResPerson));
            }
            int totalCount = list.Count();
            int pageCount = (int)Math.Ceiling(totalCount * 1.0 / request.pageSize);
            var pagelist = list.OrderByDescending(x => x.Id).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();
            return new PageResult<FuelCosts>
            {
                List = pagelist,
                PageCount = pageCount,
                TotalCount = totalCount
            };
        }
    }
}
